package com.example.administrator.myrxjavademo.net;


import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import rx.Subscriber;

/**
 * Created by helin on 2016/10/10 15:49.
 */

public abstract class ProgressSubscriber<T> extends Subscriber<T> {

    private ProgressDialog pd;
    private Context mContext;
    private boolean mIsShowProgressDialog = true;

    @Override
    public void onStart() {
        super.onStart();
        if (mIsShowProgressDialog)
            initProgressDialog();
        showProgressDialog();
    }

    public ProgressSubscriber() {
    }

    public ProgressSubscriber(boolean isShowProgressDialog) {
        mIsShowProgressDialog = isShowProgressDialog;
    }

    public ProgressSubscriber(Context context) {
        mContext = context;
    }

    public ProgressSubscriber(Context context, boolean isShowProgressDialog) {
        mContext = context;
        mIsShowProgressDialog = isShowProgressDialog;
    }

    /**
     * 取消ProgressDialog的时候，取消对observable的订阅，同时也取消了http请求
     */
    public void onCancelProgress() {
        if (!this.isUnsubscribed()) {
            this.unsubscribe();
        }
        dismissProgressDialog();
    }

    /**
     * 隐藏
     */
    public void dismissProgressDialog() {
        if (pd != null && pd.isShowing()) {
            pd.dismiss();
        }
        mContext = null;
    }

    /**
     * 初始化加载框
     */
    private void initProgressDialog() {
        if (pd == null) {
            if (mContext != null) {
                pd = new ProgressDialog(mContext);
                pd.setCancelable(false);
                pd.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialogInterface) {
                        onCancelProgress();
                    }
                });
            }
        }
    }

    /**
     * 显示加载框
     */
    private void showProgressDialog() {
        if (pd != null && !pd.isShowing()) {
            pd.show();
        }
    }


    @Override
    public void onCompleted() {
        dismissProgressDialog();
    }

    @Override
    public void onError(Throwable e) {
        if (e instanceof SocketTimeoutException) {
//            Toast.makeText(context, "网络中断，请检查您的网络状态", Toast.LENGTH_SHORT).show();
        } else if (e instanceof ConnectException) {
//            Toast.makeText(context, "网络中断，请检查您的网络状态", Toast.LENGTH_SHORT).show();
        } else {
            String message = e.getMessage();
//            Toast.makeText(context, "error:" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        dismissProgressDialog();
    }

}
